package ru.mipt.sport.gui.model;

import java.util.List;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import ru.mipt.sport.model.interfaces.CompetitionRun;
import ru.mipt.sport.model.interfaces.RunResult;
import ru.mipt.sport.utils.DBUtils;

/**
 *
 * @author danon
 */
public class RunResultsTableModel implements TableModel {

    private final DBUtils db = DBUtils.getInstance();
    private List<RunResult> elements = null;
    private CompetitionRun run;
    
    public RunResultsTableModel(CompetitionRun r) {
        this.run = r;
        refresh();
    }
    
    

    @Override
    public int getRowCount() {
        return elements.size();
    }

    @Override
    public int getColumnCount() {
        return 3;
    }

    @Override
    public String getColumnName(int columnIndex) {
        switch(columnIndex) {
            case 0 : return "Name";
            case 1 : return "Team";
            case 2 : return "Result";
            case 3 : return "Units";
        }
        return null;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        switch(columnIndex) {
            case 0 : return String.class;
            case 1 : return String.class;
            case 2 : return String.class;
            case 3 : return String.class;
        }
        return null;
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        switch(columnIndex) {
            case 0 : return elements.get(rowIndex).getName();
            case 1 : return elements.get(rowIndex).getTeam();
            case 2 : return elements.get(rowIndex).getTotalValue();
            case 3 : return elements.get(rowIndex).getUnits();
        }
        return null;
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void addTableModelListener(TableModelListener l) {
        
    }

    @Override
    public void removeTableModelListener(TableModelListener l) {
        
    }
    
    public final void refresh() {
        synchronized(db) {
            elements = db.getEntityManager()
                    .createQuery("select r from RunResultEntity r where r.competitionRun = :run",
                    RunResult.class).setParameter("run", run).getResultList();
        }
    }

    public RunResult removeRow(int i) {
        return elements.remove(i);
    }

    public RunResult getElementAt(int i) {
        return elements.get(i);
    }
    
}
